package com.extension.company.model.home;

import android.content.Context;
import android.util.Log;

import com.extension.company.Constant;
import com.extension.company.KEY;
import com.extension.company.common.http.RetrofitHelper;
import com.extension.company.common.utils.MD5;
import com.extension.company.common.utils.ToastUtil;
import com.extension.company.contract.home.OnlineWaitForPaymentContract;
import com.extension.company.eventbus.OrderId;
import com.extension.company.model.api.RetrofitUrlApi;
import com.extension.company.model.entity.AddressListData;
import com.extension.company.model.entity.OrderConfirmBean;
import com.extension.company.model.entity.OrderConfirmCarListBean;
import com.extension.company.model.entity.PayForInfor;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者:zwk
 * 联系方式：497981239@qq.com
 * 时间：on 2019/8/6 08:51
 * 功能：待支付的model
 */
public class OnlineWaitForPayActivityModel implements OnlineWaitForPaymentContract.model {

	private RetrofitUrlApi retrofitUrlApi = RetrofitHelper.getRetrofit().create(RetrofitUrlApi.class);
	private IWXAPI api;
	private String orderId;

	@Override
	public void requestDefaultAddress(final OnlineWaitForPaymentContract.DefaultAddressCallbak callbak) { // 请求默认的收货地址
		retrofitUrlApi.AddressList(Constant.SIGN, Constant.TOKEN)
				.observeOn(AndroidSchedulers.mainThread())
				.subscribeOn(Schedulers.io())
				.subscribe(new Observer<AddressListData>() {
					@Override
					public void onSubscribe(Disposable d) {
					}

					@Override
					public void onNext(AddressListData addressListData) {
						if (200 == addressListData.getCode()) {
							for (int i = 0; i < addressListData.getData().getAddress().size(); i++) {
								if ("1".equals(addressListData.getData().getAddress().get(i).getIs_default())) {
									callbak.m2p(addressListData.getData().getAddress().get(i).getPhone(),
											addressListData.getData().getAddress().get(i).getName(),
											addressListData.getData().getAddress().get(i).getPname()
													+ addressListData.getData().getAddress().get(i).getCname()
													+ addressListData.getData().getAddress().get(i).getRname()
													+ addressListData.getData().getAddress().get(i).getDetail());
								}
							}
						}
					}

					@Override
					public void onError(Throwable e) {
					}

					@Override
					public void onComplete() {

					}
				});
	}

	@Override
	public void payForOrder(final Context context, String goodId, String goodSpecId, String num, final OnlineWaitForPaymentContract.PayForOrderIdCallback callback) {
		api = WXAPIFactory.createWXAPI(context, KEY.WX_PAY_ID); // 微信支付初始化
		api.registerApp(KEY.WX_PAY_ID);
		retrofitUrlApi.payForInfor(Constant.SIGN, Constant.TOKEN, goodId, goodSpecId, num)
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Observer<PayForInfor>() {
					@Override
					public void onSubscribe(Disposable d) {

					}

					@Override
					public void onNext(PayForInfor payForInfor) {
						if (payForInfor.getCode() == 200) {
							String appid = payForInfor.getData().getAppid();
							String mchid = payForInfor.getData().getMch_id(); // 后台返回的商户号
							String nonceStr = payForInfor.getData().getNonce_str().get_$0(); // 后台的随机数
							String sign = payForInfor.getData().getSign().get_$0(); //后台返回的sign签名，需要本地处理
							String prePay = payForInfor.getData().getPrepay_id().get_$0();
							orderId = payForInfor.getData().getOut_trade_no(); //传送订单id
							// 回调接口
							EventBus.getDefault().postSticky(new OrderId(orderId));
							callback.orderIdCallback(orderId);

							PayReq req = new PayReq();
							req.appId = appid; // 你的微信的ID
							req.partnerId = mchid;  // 商户号
							req.prepayId = prePay;  // 预支付的交易会话id
							req.nonceStr = nonceStr;  // 随机生成的数字
							String time = String.valueOf(System.currentTimeMillis() / 1000); // 时间戳-秒
							req.timeStamp = time;  // 时间戳
							req.packageValue = "Sign=WXPay"; // 固定的填WXPay
							req.sign = signNum(mchid, prePay, "Sign=WXPay", nonceStr, time, KEY.WX_PAY_KEY);   // 签名
							api.sendReq(req);


						} else if (payForInfor.getCode() == 400) {
							ToastUtil.showToast(context, payForInfor.getMsg());
						}

					}

					@Override
					public void onError(Throwable e) {

					}

					@Override
					public void onComplete() {

					}
				});
	}

	@Override
	public void orderConfirmCarList(String goodsInfo, String areaId, final OnlineWaitForPaymentContract.OrderConfirmListCallback callback) {
		retrofitUrlApi
				.carList(Constant.SIGN, Constant.TOKEN, goodsInfo, areaId)
				.observeOn(AndroidSchedulers.mainThread())
				.subscribeOn(Schedulers.io())
				.subscribe(new Observer<OrderConfirmCarListBean>() {
					@Override
					public void onSubscribe(Disposable d) {

					}

					@Override
					public void onNext(OrderConfirmCarListBean orderConfirmCarListBean) {
						if (200 == orderConfirmCarListBean.getCode()) {
							callback.orderConfirmCallback(orderConfirmCarListBean.getData());
						}
					}

					@Override
					public void onError(Throwable e) {

					}

					@Override
					public void onComplete() {

					}
				});
	}

	/**
	 * @param partnerId    商户名
	 * @param prepayId     预支付交易id
	 * @param packageValue Sing=WXPay
	 * @param nonceStr     随机数
	 * @param timeStamp    时间戳
	 * @param key          商户的key
	 * @return 加密后的sign
	 */
	private String signNum(String partnerId, String prepayId, String packageValue, String nonceStr, String timeStamp, String key) {
		String stringA =
				"appid=" + KEY.WX_PAY_ID
						+ "&noncestr=" + nonceStr
						+ "&package=" + packageValue
						+ "&partnerid=" + partnerId
						+ "&prepayid=" + prepayId
						+ "&timestamp=" + timeStamp;
		String stringSignTemp = stringA + "&key=" + key;
		return MD5.getMessageDigest(stringSignTemp.getBytes()).toUpperCase();
	}

}
